import datetime

from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
import re

from pymysql import DatabaseError
from django.contrib.auth.mixins import LoginRequiredMixin
from apps.index.models import User
from apps.user.models import Article


class IndexView(LoginRequiredMixin,View):
    def get(self, request):
        list1 = []
        user = request.user.username
        article = Article.objects.all()
        other_users = User.objects.exclude(username=user)

        context = {
            'contents': other_users,
            'article': article,
        }

        return render(request, 'index.html', context)

    def post(self, request):
        title = request.POST.get('title')
        description = request.POST.get('description')
        try:
            Article.objects.create(title=title, content=description, user=request.user, create_time2=str(datetime.datetime.now())[0:19])
        except DatabaseError:
            messages.success(request, "发布失败")
            return render(request, 'index.html')
        messages.success(request, "发布成功")
        response = redirect(reverse('index:index'))
        return response





